package com.gewu.pm.ui.activity.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.ui.activity.ImageSelectActivity;
import com.gewu.pm.ui.adapter.order.ImageUploadAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 收款登记页面
 */
public final class PaymentRegistrationActivity extends AppActivity
        implements ImageSelectActivity.OnPhotoSelectListener {

    private static final int MAX_IMAGE_COUNT = 6;  // 最多6张图片

    // 标签
    private TextView tvTerminalLabel;
    private TextView tvPaymentTypeLabel;
    private TextView tvPaymentDateLabel;
    private TextView tvVehicleLabel;
    private TextView tvOperatorLabel;
    private TextView tvSubmitterLabel;
    private TextView tvVoucherLabel;
    private TextView tvVoucherImageLabel;

    // 值
    private TextView tvTerminalValue;
    private TextView tvPaymentTypeValue;
    private TextView tvPaymentDateValue;
    private TextView tvVehicleValue;
    private TextView tvOperatorValue;
    private TextView tvSubmitterValue;

    // 输入框
    private EditText etRemark;
    private EditText etVoucherNumber;

    // 图片相关
    private RecyclerView rvImages;
    private ImageUploadAdapter imageAdapter;
    private final List<String> imageList = new ArrayList<>();

    // 底部
    private TextView tvTotalAmount;
    private TextView btnSubmit;
    
    // 点击区域
    private LinearLayout llViewDocuments;

    public static void start(Context context) {
        Intent intent = new Intent(context, PaymentRegistrationActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.payment_registration_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 初始化标签
        tvTerminalLabel = findViewById(R.id.tv_terminal_label);
        tvPaymentTypeLabel = findViewById(R.id.tv_payment_type_label);
        tvPaymentDateLabel = findViewById(R.id.tv_payment_date_label);
        tvVehicleLabel = findViewById(R.id.tv_vehicle_label);
        tvOperatorLabel = findViewById(R.id.tv_operator_label);
        tvSubmitterLabel = findViewById(R.id.tv_submitter_label);
        tvVoucherLabel = findViewById(R.id.tv_voucher_label);
        tvVoucherImageLabel = findViewById(R.id.tv_voucher_image_label);

        // 初始化值
        tvTerminalValue = findViewById(R.id.tv_terminal_value);
        tvPaymentTypeValue = findViewById(R.id.tv_payment_type_value);
        tvPaymentDateValue = findViewById(R.id.tv_payment_date_value);
        tvVehicleValue = findViewById(R.id.tv_vehicle_value);
        tvOperatorValue = findViewById(R.id.tv_operator_value);
        tvSubmitterValue = findViewById(R.id.tv_submitter_value);

        // 输入框
        etRemark = findViewById(R.id.et_remark);
        etVoucherNumber = findViewById(R.id.et_voucher_number);

        // 图片
        rvImages = findViewById(R.id.rv_images);

        // 底部
        tvTotalAmount = findViewById(R.id.tv_total_amount);
        btnSubmit = findViewById(R.id.btn_submit);
        
        // 点击区域
        llViewDocuments = findViewById(R.id.ll_view_documents);

        // 设置必填标记（红色星号）
        setRequiredText(tvTerminalLabel, "终端名称");
        setRequiredText(tvPaymentTypeLabel, "收款类型");
        setRequiredText(tvPaymentDateLabel, "收款日期");
        setRequiredText(tvVehicleLabel, "车辆编码");
        setRequiredText(tvOperatorLabel, "经办人");
        setRequiredText(tvSubmitterLabel, "提交人");
        setRequiredText(tvVoucherLabel, "凭证编号");
        setRequiredText(tvVoucherImageLabel, "收款凭证");

        // 设置图片网格（2行3列）
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        rvImages.setLayoutManager(gridLayoutManager);

        // 设置图片适配器
        imageAdapter = new ImageUploadAdapter(this, MAX_IMAGE_COUNT, position -> {
            // 删除图片
            imageList.remove(position);
            updateImageList();
        });
        // 设置占位图为 add_ic
        imageAdapter.setPlaceholderResId(R.drawable.add_ic);
        // 启用占位文字显示
        imageAdapter.setShowPlaceholderText(true);
        imageAdapter.setPlaceholderTextPrefix("上传图片");
        
        // 设置添加图片监听
        imageAdapter.setOnAddListener(() -> {
            // 打开图片选择
            openImageSelect();
        });
        
        rvImages.setAdapter(imageAdapter);

        // 设置点击事件
        setOnClickListener(btnSubmit, llViewDocuments);
    }

    @Override
    protected void initData() {
        // 初始化图片列表（添加相机图标作为第一项）
        updateImageList();
    }

    /**
     * 为 TextView 设置必填文本（红色星号）
     */
    private void setRequiredText(TextView textView, String text) {
        String requiredText = "* " + text;
        SpannableString spannableString = new SpannableString(requiredText);
        
        // 设置星号为红色
        spannableString.setSpan(
                new ForegroundColorSpan(getResources().getColor(R.color.red_app)),
                0, 1,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        );
        
        textView.setText(spannableString);
    }

    /**
     * 更新图片列表
     */
    private void updateImageList() {
        // 创建显示列表
        List<String> displayList = new ArrayList<>(imageList);
        
        // 如果未满6张，添加相机图标
        if (imageList.size() < MAX_IMAGE_COUNT) {
            displayList.add("camera");  // 用特殊标记代表相机图标
        }
        
        imageAdapter.setData(displayList);
    }

    /**
     * 打开图片选择
     */
    private void openImageSelect() {
        int remainCount = MAX_IMAGE_COUNT - imageList.size();
        if (remainCount > 0) {
            ImageSelectActivity.start(this, remainCount, this);
        } else {
            toast("最多只能选择" + MAX_IMAGE_COUNT + "张图片");
        }
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == btnSubmit) {//提交
            PayOrderActivity.start(getActivity(), "¥4468.80");
            // 打印选择的图片路径  这个是测试路径  到时候会用到
/*            if (imageList.isEmpty()) {
                toast("请至少上传一张收款凭证");
            } else {
                StringBuilder sb = new StringBuilder("选择的图片路径：\n");
                for (int i = 0; i < imageList.size(); i++) {
                    sb.append((i + 1)).append(". ").append(imageList.get(i)).append("\n");
                }
                toast(sb.toString());
                
                // 同时在 Logcat 中打印
                LogUtils.d("PaymentRegistration", "====== 选择的图片 ======");
                for (int i = 0; i < imageList.size(); i++) {
                    LogUtils.d("PaymentRegistration", "图片" + (i + 1) + ": " + imageList.get(i));
                }
                LogUtils.d("PaymentRegistration", "总共: " + imageList.size() + " 张图片");
            }*/
        } else if (view == llViewDocuments) {
            // 跳转到查看单据页面
            ViewDocumentsActivity.start(this);
        }
    }

    /**
     * {@link ImageSelectActivity.OnPhotoSelectListener}
     * 图片选择回调
     */
    @Override
    public void onSelected(List<String> images) {
        if (images != null && !images.isEmpty()) {
            imageList.addAll(images);
            updateImageList();
        }
    }

    @Override
    public void onCancel() {
        // 取消选择
    }
}

